﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web;
using System.IO;
using System.Text;
using Common;


//1、拍照请求：
//http://192.168.121.248:82/hik_robot/camera/get_image   
//请求参数
//device = 设备ip

//2、AI识别请求：
//(钢胚识别)http://192.168.121.248:81/code/track_number
//(卷芯架识别)http://192.168.121.248:81/code/track_shelf_number
//(C型钩识别)http://192.168.121.248:81/code/track_hanger_number
//请求参数
//imageUrl = 图片地址 也就是上面拍照请求返回的oss地址
//  range = 识别范围(可选参数)
//rotate=旋转角度(可选参数)


/*
 * 打标机
 */

namespace MySqlApi.Controllers
{
    [RoutePrefix("api/PicNum")]
    public class DbjController : ApiController
    {

        string ps_name = "PostGetPicNum";

      



        [HttpPost]
        [Route("PostGetPicNum")]
        public System.Data.DataSet PostGetPicNum([FromBody]  JObject obj)
        {

            



            DateTime dt0 = DateTime.Now;
            DateTime dt1 = DateTime.Now;
            TimeSpan timeDifference;
            int subTime = 0;
          

            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables[0].TableName = "SYS";
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Columns.Add("EXIST");
            outBlock.Tables["SYS"].Columns.Add("NUM");
            outBlock.Tables["SYS"].Columns.Add("EXIST_IMG");
            outBlock.Tables["SYS"].Columns.Add("NUM_IMG");


            string flag = "-1";
            string msg = "";
            string exist = "";
            string num = "";
            string exist_img = "";
            string num_img = "";


             


            string IP   = obj["IP"] == null ? "0" : obj["IP"].ToString().ToUpper();
            string IP_CODE = obj["IP_CODE"] == null ? " " : obj["IP_CODE"].ToString().Trim(); 
            string TYPE = obj["TYPE"] == null ? "" : obj["TYPE"].ToString().Trim();



            string ip = IP; 
            int IntIp = int.Parse(ip.Replace("10.97.36.", "")); 
            ps_name = ip + "_" + ps_name;
            

            int i = get_order2.get_order_num(IntIp);


            if (TYPE!="IN" 
                && TYPE != "OUT"
                )
            {
                flag = "-1";
                msg = "TYPE错误[" + TYPE + "]" ;

                ClassMyFile.WriteLog(msg, ps_name);
                ClassMyFile.WriteLog(ip + "," + msg, "PicNumError0入口参数错误");

                outBlock.Tables["SYS"].Rows.Add(flag, msg, exist, num, exist_img, num_img);
                return outBlock;
            }
         





         




            ClassMyFile.WriteLog("i="+i.ToString()+ ",begin-------------------------------------------------上次执行时间：" + get_order2.get_dt_last(IntIp).ToString("yyyy-MM-dd HH:mm:ss")+ "", ps_name);

            ClassMyFile.WriteLog("obj.ToString()：" + obj.ToString() + "", ps_name);


             



            //1逻辑校验；防止一直接口调用； 
            timeDifference = DateTime.Now - get_order2.get_dt_last(IntIp);
            subTime = timeDifference.Hours * 3600 + timeDifference.Minutes * 60 + timeDifference.Seconds;

            if (subTime <=  3)
            {
                flag = "-1";
                msg = "请求间隔不得少于3秒！上次执行时间：" + get_order2.get_dt_last(IntIp).ToString("yyyy-MM-dd HH:mm:ss"); 

                ClassMyFile.WriteLog(msg, ps_name); 
                ClassMyFile.WriteLog(ip+"," +  msg, "PicNumError1信号逻辑");  

                outBlock.Tables["SYS"].Rows.Add(flag, msg, exist, num, exist_img, num_img);
                return outBlock;
            }

            get_order2.set_dt_last(IntIp);




            dt1 = DateTime.Now;
            ClassMyFile.WriteLog("get_imageUrl begin", ps_name);



            List<string> imageUrl = ClassL2Ai.get_imageUrl2(ip, TYPE);

           


           


            //防止图片打开错误，共执行3次；每次间隔0.2秒；
            int count = 1;
            while (imageUrl.Count == 0  && count < 3)
            {
                count++;
                System.Threading.Thread.Sleep(200);
                imageUrl = ClassL2Ai.get_imageUrl2(ip, TYPE);
            }

            timeDifference = DateTime.Now - dt1;
            subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;


            ClassMyFile.WriteLog(string.Format("get_imageUrl,耗时{0}ms, 第[{1}]次拍照", subTime, count), ps_name);

            dt1 = DateTime.Now;


            if (imageUrl.Count == 0)
            {
                flag = "-1";
                msg = string.Format("-1 get_imageUrl，照片抓取识别,IP{0}]", ip );
                ClassMyFile.WriteLog(msg, ps_name); 
                ClassMyFile.WriteLog(ip + "," + msg, "PicNumError2拍照服务"); 
               
                outBlock.Tables["SYS"].Rows.Add(flag, msg, exist, num, exist_img, num_img);
                return outBlock;
            }


            foreach (var item in imageUrl)
            {
                ClassMyFile.WriteLog(string.Format("imageUrl=\n{0}", item), ps_name);
            }

            ClassMyFile.WriteLog("get_imageUrl end", ps_name);






            //foreach (var item in dynamicArray)
            for (int k=0;k< imageUrl.Count();k++)
            {

                string img_rul = imageUrl[k];

                if (img_rul!=null && img_rul.Contains("EXIST"))
                {
                    exist_img = img_rul;

                    ClassMyFile.WriteLog("get_pic_ocr_exist begin  ", ps_name);
                    exist = ClassL2Ai.get_imageOcr(img_rul, "EXIST");
                    if (exist == "-1")
                    {
                        flag = "-1";
                        msg = "是否有料识别服务异常";

                        ClassMyFile.WriteLog(msg, ps_name);
                        ClassMyFile.WriteLog(ip + "," + msg, "PicNumError31EXIST识别服务"); 
                        outBlock.Tables["SYS"].Rows.Add(flag, msg, exist, num, exist_img, num_img);  
                        return outBlock;
                    }
                    timeDifference = DateTime.Now - dt1;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_pic_ocr_exist end,耗时{0}ms ,str_num=[{1}]", subTime, exist), ps_name);
                    dt1 = DateTime.Now;

                }
                else if (img_rul != null && img_rul.Contains("NUM"))
                {
                    num_img = img_rul; 

                    ClassMyFile.WriteLog("get_pic_ocr_num begin  ", ps_name);


                    num = ClassL2Ai.get_imageOcr(num_img, "NUM");

                    if (num == "-1")
                    {
                        flag = "-1";
                        msg = "钩号识别服务异常";

                        ClassMyFile.WriteLog(msg, ps_name);
                        ClassMyFile.WriteLog(ip + "," + msg, "PicNumError32NUM识别服务");
                        outBlock.Tables["SYS"].Rows.Add(flag, msg, exist, num, exist_img, num_img);
                        return outBlock; 
                    } 

                    timeDifference = DateTime.Now - dt1;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_pic_ocr_num end,耗时{0}ms ,str_num=[{1}]", subTime, num), ps_name);
                    dt1 = DateTime.Now;
                } 
            }


            



            timeDifference = DateTime.Now - dt0;
            

            subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;

           

            ClassMyFile.WriteLog(string.Format("end,总耗时{0}ms  \n", subTime), ps_name);

           





            flag = "0";
            msg = "success";
            outBlock.Tables["SYS"].Rows.Add(flag, msg, exist, num, exist_img, num_img);



            return outBlock;

        }


         


         


 


         




    }



   
    
}